package com.hd.trans.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

import com.airbnb.lottie.LottieAnimationView;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.Constants;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.ConfirmDialog;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.ui.activity.SimulHomeActivity3;
import com.hd.trans.ui.component.HdRecognitionComponent;
import com.hd.trans.ui.component.RecognitionCallBack;
import com.hd.trans.ui.component.RecordFileCallback;
import com.hd.trans.ui.model.SimultaneousModel;
import com.hd.trans.utils.ScreenUtil;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.widgets.ImageTextView;
import com.hd.trans.widgets.VoiceLineViewwhite;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("SetTextI18n")
public class SimulInterpretFragment3 extends SimulBaseFragment implements View.OnClickListener {
    private SimulHomeActivity3 mActivity;
    private ImageView btnTransform;
    private ImageView close;
    private ImageView rotate;
    private RelativeLayout rotateLayout;
    private LinearLayout _voiceIcon, _voiceIcon2;
    private LinearLayout voiceIcon, voiceIcon2;
    private TextView beginSpeech, beginSpeech2;
    private TextView _originalText;
    private TextView originalText;
    private TextView tvToast;
    private Switch switchView;
    private ImageView ivStartAndStop;
    private ImageView waveLine;
    private ImageTextView radioButton;
    private LinearLayout fromBt,toBt;
    private ImageView exchange;
    private TextView tvFrom,tvTo;
    private TextView tvTips;
    private TextView tvTips2;

    private Chronometer timeChronometer;
    private VoiceLineViewwhite voiceWaveView;
    private ImageView copyOriginal;
    private TextView _translationText;
    private TextView translationText;
    private View _maskedView, _maskedView2;
    private View maskedView, maskedView2;
    private ImageView copyTranslated;
    private HdRecognitionComponent mRecognitionComponent; //语音识别组件
    private HdTranslateComponent mTranslateComponent;  //  文本翻译组件
    public SimultaneousModel mDataModel;
    private ClipboardManager clipMgr;//粘贴板控制
    private NestedScrollView originalScroll;
    private NestedScrollView transScroll;
    private View parentLayout;
    private View bottomLayout;
    private View rlLang;
    private View _parsingLayout,_parsingLayout2;
    private View parsingLayout,parsingLayout2;
    private LottieAnimationView _lottie1,_lottie2;
    private LottieAnimationView lottie1,lottie2;
    private Handler mHandler;
    private boolean isStarting = true;
    private AnimationDrawable animationDrawable;
    private List<Subsection> subsectionList;
    private Subsection currentSubsection;
    private Subsection lastSubsection;
    private ConfirmDialog dialog;
    private boolean isChecked = false;
    private int showTypeOneCount = 1;
    private int showTypeTwoCount = 0;
    private int screenWidth;
    private boolean isAllowScroll;
    private boolean isAllowSaveRecording;
    private boolean showItFirstTime;
    private boolean isHasNotSaved;
    private boolean isVip;
    private long startTime = 0;

    public SimulInterpretFragment3(SimultaneousModel mDataModel) {
        this.mDataModel = mDataModel;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TranslationInterior.getTrackerListener().view(TrackerForTrans.TSCY + TrackerForTrans.TRANS_PAGE);
        mActivity = (SimulHomeActivity3) getActivity();
        screenWidth = ScreenUtil.getScreenWidth(mActivity);
        View view = inflater.inflate(R.layout.fragment_simul_interpret3, container, false);
        initView(view);
        setThemeColor();//给改变换颜色的控件换颜色
        return view;
    }

    private void transform() {
        int tag = (int) btnTransform.getTag();
        if(tag==2){
            originalText = _translationText;
            translationText = _originalText;
            if(switchView.isChecked()){
                parsingLayout = _parsingLayout2;
                parsingLayout2 = _parsingLayout;
                lottie1 = _lottie2;
                lottie2 = _lottie1;
                voiceIcon = _voiceIcon2;
                voiceIcon2 = _voiceIcon;
            }else {
                parsingLayout = _parsingLayout;
                parsingLayout2 = _parsingLayout2;
                lottie1 = _lottie1;
                lottie2 = _lottie2;
                voiceIcon = _voiceIcon;
                voiceIcon2 = _voiceIcon2;
            }
            maskedView = _maskedView2;
            maskedView2 = _maskedView;
        }else {
            originalText = _originalText;
            translationText = _translationText;
            parsingLayout = _parsingLayout;
            parsingLayout2 = _parsingLayout2;
            lottie1 = _lottie1;
            lottie2 = _lottie2;
            voiceIcon = _voiceIcon;
            voiceIcon2 = _voiceIcon2;
            maskedView = _maskedView;
            maskedView2 = _maskedView2;
        }

        changeHintText();
        changeOriginalText("");
        changeTranslationText();
        showLottieAnimation1(switchView.isChecked());
        showLottieAnimation2(!switchView.isChecked());
        voiceIcon.setVisibility(TextUtils.isEmpty(originalText.getText())?View.VISIBLE:View.GONE);
        voiceIcon2.setVisibility(View.GONE);
        maskedView.setVisibility(mActivity.isVip()?View.GONE:View.VISIBLE);
        maskedView2.setVisibility(View.GONE);
    }

    private void initView(View view) {
        mHandler = new Handler();
        currentSubsection = new Subsection();
        lastSubsection = new Subsection();
        subsectionList = new ArrayList<>();
        subsectionList.add(currentSubsection);
        btnTransform = view.findViewById(R.id.btn_transform);
        close = view.findViewById(R.id.close);
        rotate = view.findViewById(R.id.ic_rotate);
        rotateLayout = view.findViewById(R.id.rotate_layout);
        _voiceIcon = view.findViewById(R.id.voice_icon);
        _voiceIcon2 = view.findViewById(R.id.voice_icon2);
        beginSpeech = view.findViewById(R.id.begin_speech);
        beginSpeech2 = view.findViewById(R.id.begin_speech2);
        _originalText = view.findViewById(R.id.original_text);
        timeChronometer = view.findViewById(R.id.time_chronometer);
        voiceWaveView = view.findViewById(R.id.voiceWaveView);
        copyOriginal = view.findViewById(R.id.copy_original);
        _translationText = view.findViewById(R.id.translation);
        _maskedView = view.findViewById(R.id.masked_view);
        _maskedView2 = view.findViewById(R.id.masked_view2);
        copyTranslated = view.findViewById(R.id.copy_translated);
        originalScroll = view.findViewById(R.id.original_scroll);
        transScroll = view.findViewById(R.id.trans_scroll);
        parentLayout = view.findViewById(R.id.root_view);
        _parsingLayout = view.findViewById(R.id.parsing_layout);
        _parsingLayout2 = view.findViewById(R.id.parsing_layout2);
        tvToast = view.findViewById(R.id.tv_toast);
        switchView = view.findViewById(R.id.switch_view);
        _lottie1 = view.findViewById(R.id.lottie1);
        _lottie2 = view.findViewById(R.id.lottie2);
        bottomLayout = view.findViewById(R.id.bottom_layout);
        ivStartAndStop = view.findViewById(R.id.iv_start_and_stop);
        waveLine = view.findViewById(R.id.wave_line);
        radioButton = view.findViewById(R.id.radio_button);
        fromBt = view.findViewById(R.id.left_bt);
        toBt = view.findViewById(R.id.right_bt);
        exchange = view.findViewById(R.id.icon_exchange);
        tvFrom = view.findViewById(R.id.tv_from);
        tvTo = view.findViewById(R.id.tv_to);
        tvTips = view.findViewById(R.id.tv_tips);
        tvTips2 = view.findViewById(R.id.tv_tips2);
        rlLang = view.findViewById(R.id.rl_lang);
        rlLang.setVisibility(View.GONE);//初始化隐藏
        isAllowSaveRecording = PreferenceMgr.getInstance().isAllowSaveChecked() && mActivity.isVip();
        radioButton.setSelected(isAllowSaveRecording);
        animationDrawable = (AnimationDrawable) waveLine.getBackground();
        //开始
        animationDrawable.start();

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.onBackPressed();
            }
        });

        switchView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //两个埋点
                TranslationInterior.getTrackerListener().click(
                        TrackerForTrans.TSCY,
                        isChecked?TrackerForTrans.COLUMNS_SHOW:TrackerForTrans.MERGE_SHOW,
                        TrackerForTrans.SHOW
                );
                TranslationInterior.getTrackerListener().click(
                        TrackerForTrans.TSCY,
                        TrackerForTrans.SWITCH_BUTTON
                );
                if(mActivity.isLimitUsed("同声传译_显示模式")){
                    setShowLottieAnimation(isChecked);
                }else {
                    switchView.setOnCheckedChangeListener(null);
                    switchView.setChecked(!isChecked);
                    switchView.setOnCheckedChangeListener(this);
                }
            }
        });
        btnTransform.setOnClickListener(this);
        rotate.setOnClickListener(this);
        copyOriginal.setOnClickListener(this);
        copyTranslated.setOnClickListener(this);
        ivStartAndStop.setOnClickListener(this);
        fromBt.setOnClickListener(this);
        toBt.setOnClickListener(this);
        exchange.setOnClickListener(this);
        radioButton.setOnClickListener(this);
        _maskedView.setOnClickListener(this);
        _maskedView2.setOnClickListener(this);

        updateButton(1);
        showTips2();

        btnTransform.setTag(1);
        transform();
    }

    public void stopRecord(){
        if(mRecognitionComponent!= null){
            mRecognitionComponent.stopRecognition();
        }
    }

    public void stopOrDestroy(){
        stopRecord();
        if(mTranslateComponent != null)
            mTranslateComponent.destroy();
    }

//    private float downX,downY,upX,upY,lastTempY,downWeight;
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent event) {
//        int action = event.getAction();
//        if(action == MotionEvent.ACTION_DOWN){
//            downX = event.getX();
//            downY = event.getY();
//            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
//            downWeight = params.weight;
//
//            isAllowScroll = downX > screenWidth*2/3;
//        }else if(action == MotionEvent.ACTION_UP){
//            if(isAllowScroll){
//                upX = event.getX();
//                upY = event.getY();
//                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
//                if(params.weight > 0.5f){
//                    if(switchView.isChecked()){
//                        mHandler.removeCallbacks(hideBottomAnimation);
//                        mHandler.removeCallbacks(showBottomAnimation);
//                        mHandler.post(showBottomAnimation);
//                    }else {
//                        switchView.setChecked(true);
//                    }
//
//                }else {
//                    if(switchView.isChecked()){
//                        switchView.setChecked(false);
//                    }else {
//                        mHandler.removeCallbacks(hideBottomAnimation);
//                        mHandler.removeCallbacks(showBottomAnimation);
//                        mHandler.post(hideBottomAnimation);
//                    }
//                }
//            }
//
//        }else if(action == MotionEvent.ACTION_MOVE){
//            if(isAllowScroll){
//                float currentX = event.getX();
//                float currentY = event.getY();
//                float tempY = downY - currentY;
//                if(lastTempY != tempY){
//                    lastTempY = tempY;
//                    float d = (downY - currentY)/10.0f * 0.01f;
//                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
//                    params.weight = downWeight+d;
//                    if(params.weight > 1){
//                        params.weight = 1.0f;
//                        bottomLayout.setLayoutParams(params);
//                    }else if(params.weight<=1 && params.weight> 0){
//                        bottomLayout.setLayoutParams(params);
//                    }else {
//                        params.weight = 0f;
//                        bottomLayout.setLayoutParams(params);
//                    }
//                    bottomLayout.invalidate();
//                }
//            }
//
//        }
//        return super.dispatchTouchEvent(event);
//    }

    /*@Override
    public void onStop() {
        super.onStop();
        if(isStarting)
            ivStartAndStop.performClick();
    }*/

    @Override
    public boolean onBackPressed() {
        if(isStarting){
            ivStartAndStop.performClick();
            return true;
        }
        if(isAllowSaveRecording){
            if(isHasNotSaved){
                return showExitDialog();
            }
        }else {
            return showExitDialog();
        }
        finishFragment();
        return true;
    }

    private boolean showExitDialog(){
        if(!PreferenceMgr.getInstance().isNeverShowThisTips()
                &&!TextUtils.isEmpty(originalText.getText().toString().trim())){
            if (dialog == null) {
                dialog = ConfirmDialog.builder()
                        .setContent(getResources().getString(R.string.confirm_tip3))
                        .rightTxt(getResources().getString(R.string.str_keep_out))
                        .setShowCheckBox(true)
                        .setChecked(isChecked)
                        .setOnCheckedChangeListener((buttonView, isChecked) -> {
                            this.isChecked = isChecked;
                        })
                        .setRightListenner(dialog ->{
                            PreferenceMgr.getInstance().setNeverShowThisTips(isChecked);
                            finishFragment();
                        })
                        .setLeftListenner(dialog -> {
                            PreferenceMgr.getInstance().setNeverShowThisTips(isChecked);
                        })
                        .build();
            }
            dialog.show(getActivity().getSupportFragmentManager(), "SimulHomeActivity");

            return true;
        }

        return false;
    }

    private void finishFragment(){
        stopOrDestroy();
        if(mActivity.isTopStyle){
            mActivity.finish();
        }else {
            mActivity.getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopOrDestroy();
        getLifecycle().removeObserver(mRecognitionComponent);
        getLifecycle().removeObserver(mTranslateComponent);

        if(mHandler != null){
            mHandler.post(hideToastRunnable);
        }

    }

    @Override
    void onlazyLoad() {

        mRecognitionComponent = new HdRecognitionComponent(mActivity, false, new RecordFileCallback() {
            private String taskId;

            @Override
            public void createRecordFile(String taskId) {
                if(isAllowSaveRecording){
                    this.taskId = taskId;
                    TranslationInterior.getRecordFileCallback().createRecordFile(taskId);
                }
            }

            @Override
            public void writeByteToFile(byte[] bytes) {
                if(isAllowSaveRecording){
                    TranslationInterior.getRecordFileCallback().writeByteToFile(bytes);
                }
            }

            @Override
            public void savePcmToWav(String taskId) {
                if(isAllowSaveRecording){
                    if(lastSubsection != null && !TextUtils.isEmpty(lastSubsection.originalContent)){
                        mHandler.post(() -> ToastUtils.showNormal("录音文件保存成功！\n请在历史记录中查看！"));
                        TranslationInterior.getRecordFileCallback().savePcmToWav(taskId);
                        TranslationInterior.getRecordFileCallback().saveRecord(
                                taskId,
                                mDataModel.getLanguageFrom().getValue().getTranslateCode(),
                                mDataModel.getLanguageTo().getValue().getTranslateCode(),
                                lastSubsection.originalContent,
                                lastSubsection.translateContent
                        );
                        lastSubsection.setOriginalContent("");
                        lastSubsection.setTranslateContent("");
                    }
                }else {
                    isHasNotSaved = true;
                }
            }

            @Override
            public void saveRecord(String taskId, String origCode, String transCode, String origContent, String transContent) {
                if(isAllowSaveRecording){
                    //
                }
            }
        });
        getLifecycle().addObserver(mRecognitionComponent);

        mTranslateComponent = new HdTranslateComponent(getActivity());
        getLifecycle().addObserver(mTranslateComponent);

        clipMgr = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        executeRecognize(false);

        mDataModel.getLanguageFrom().observe(mActivity, huDunLanguage -> {
            if (huDunLanguage != null) {
                toTalkingTips(isStarting);
                tvFrom.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getLanguageTo().observe(mActivity, huDunLanguage -> {
            if (huDunLanguage != null) {
                tvTo.setText(huDunLanguage.getName());
            }
        });
    }

    private void toTalkingTips(boolean isStarting) {
        if ("英语".equals(mDataModel.getLanguageFrom().getValue().getName())) {
            if(isStarting){
                beginSpeech.setText("Please start talking");
                beginSpeech2.setText("Please start talking");
            }else {
                if(isRotate){
                    beginSpeech.setText("Click the button at the up right to start talking");
                }else {
                    beginSpeech.setText("Click the button at the bottom left to start talking");
                }
                beginSpeech2.setText("Click the button at the top left to start talking");
            }
        } else {
            if(isStarting){
                beginSpeech.setText("请开始说话吧");
                beginSpeech2.setText("请开始说话吧");
            }else {
                if(isRotate){
                    beginSpeech.setText("点击右上方按键后开始说话");
                }else {
                    beginSpeech.setText("点击左下方按键后开始说话");
                }
                beginSpeech2.setText("点击左上方按键后开始说话");
            }
        }
    }

    @Override
    void onDataFresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if(!mActivity.isVip()){
            maskedView.setVisibility(View.VISIBLE);
        }else {
            maskedView.setVisibility(View.GONE);
        }
    }


    /**
     * 语音识别
     * isReverse 是否为逆向翻译
     */
    private void executeRecognize(boolean isReverse) {
        mHandler.postDelayed(showToastRunnable, 5000);
        mHandler.post(showTipsRunnable);
        isSucceed = false;
        timeChronometer.setBase(SystemClock.elapsedRealtime());
        timeChronometer.start();
        startTime = System.currentTimeMillis();

        mRecognitionComponent.voiceRecognition(mDataModel.getLanguageFrom().getValue(), new RecognitionCallBack() {
            @Override
            public void onRecognitionFailed(String msg, int code) {
                stopRecording();
                mHandler.post(hideToastRunnable);
                Toast.makeText(mActivity, R.string.voice_service_busy, Toast.LENGTH_SHORT).show();
                startTime = 0;
            }

            @Override
            public void onRecognitionCompleted(String msg, int code) {
                //根据翻译是否有成功，保存使用掉的时间。
                if(startTime > 0){
                    mActivity.saveUseTime(System.currentTimeMillis() - startTime);
                    startTime = 0;
                }
            }

            @Override
            public void onRecognitionChanged(String msg, int code, boolean sentenceOver, String sentence) {
                if(TextUtils.isEmpty(sentence.trim())) return;
                mHandler.removeCallbacks(subsectionRunnable);
                mHandler.postDelayed(subsectionRunnable,3000);
                changeOriginalText(msg);
                if (sentenceOver) {
                    executeTranslate(sentence);
                }
                voiceIcon.setVisibility(View.GONE);
//                originalScroll.postDelayed(() -> originalScroll.fullScroll(View.FOCUS_DOWN), 10);
//                transScroll.postDelayed(() -> transScroll.fullScroll(View.FOCUS_DOWN), 10);
                mHandler.post(hideToastRunnable);
            }

            @Override
            public void onVoiceChanged(int waveBytes, int readBytes) {
                /*double dB = 10 * Math.log10(waveBytes / (double) readBytes);
                voiceWaveView.setVolume((int) (dB));*/
            }
        });
    }

    private Runnable showToastRunnable = new Runnable() {
        @Override
        public void run() {
            if(voiceIcon.getVisibility() == View.VISIBLE || isStarting){
                mHandler.removeCallbacks(hideToastRunnable);
                tvToast.setVisibility(View.VISIBLE);
            }
        }
    };

    private Runnable hideToastRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(showToastRunnable);
            tvToast.setVisibility(View.GONE);
        }
    };

    private Runnable showTipsRunnable = new Runnable() {
        @Override
        public void run() {
            if(isStarting){
                showTypeOneCount ++;
                if(showTypeOneCount>2){
                    mHandler.removeCallbacks(hideTipsRunnable);
                    tvTips.setVisibility(View.GONE);
                    return;
                }
            }else {
                showTypeTwoCount ++;
                if(showTypeTwoCount>1){
                    mHandler.removeCallbacks(hideTipsRunnable);
                    tvTips.setVisibility(View.GONE);
                    return;
                }
            }

            String tips = "";
            if(isAllowSaveRecording){
                tips = mActivity.getResources().getString(isStarting?R.string.record_stop2:R.string.record_start);
            }else {
                tips = mActivity.getResources().getString(isStarting?R.string.record_stop:R.string.record_start);
            }

            tvTips.setText(tips);

            tvTips.setVisibility(View.VISIBLE);
            tvToast.setVisibility(View.GONE);

            mHandler.removeCallbacks(hideTipsRunnable);
            mHandler.postDelayed(hideTipsRunnable,5000);
        }
    };

    private Runnable hideTipsRunnable = new Runnable() {
        @Override
        public void run() {
            tvTips.setVisibility(View.GONE);
        }
    };

    /**
     * 分段显示
     */
    private Runnable subsectionRunnable = new Runnable() {
        @Override
        public void run() {
            if(currentSubsection == null)return;
            try {
                Subsection subsection = currentSubsection.clone();
                if(!TextUtils.isEmpty(subsection.getOriginalContent())
                        || !TextUtils.isEmpty(subsection.getTranslateContent())){
                    subsectionList.add(subsectionList.size()-1,subsection);
                    recordContent();
                    currentSubsection.setOriginalContent("");
                    currentSubsection.setTranslateContent("");
                }
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }


    //记录是否翻译成功
    private boolean isSucceed;

    /**
     * 执行翻译
     */
    private void executeTranslate(String record) {
        if (TextUtils.isEmpty(record)) return;
        if(mDataModel.getLanguageTo().getValue() == null
                || mDataModel.getLanguageFrom().getValue() == null){
            return;
        }
        String fromTranslateCode = mDataModel.getLanguageFrom().getValue().getTranslateCode();
        String toTranslateCode = mDataModel.getLanguageTo().getValue().getTranslateCode();

        mTranslateComponent.translationText(
                mActivity,
                record,
                fromTranslateCode,
                toTranslateCode,
                PreferenceMgr.getInstance().isOpenOfflineTrans(),
                new TranslateCallback() {
                    @Override
                    public void onTranslateFailed(int code, String msg) {
                        if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                || code == Constants.ResponseCode.ERROR_COMM){
                            ToastUtils.showError(msg);
                        }else {
                            ToastUtils.showError(R.string.fanyi_faith_tip);
                        }
                    }

                    @Override
                    public void onTranslateCompleted(
                            String data,
                            String fromLangCode,
                            String toLangCode,
                            boolean status) {
                        isSucceed = true;
                        if(currentSubsection != null){
                            final String originalContent = currentSubsection.getOriginalContent() + record;
                            final String translateContent = currentSubsection.getTranslateContent() + data.replace("\n","");
                            currentSubsection.setOriginalContent(originalContent);
                            currentSubsection.setTranslateContent(translateContent);

                            lastSubsection.setOriginalContent(lastSubsection.originalContent + record);
                            lastSubsection.setTranslateContent(lastSubsection.translateContent + data.replace("\n", ""));

                        }
                        changeOriginalText("");
                        changeTranslationText();
                    }
                });

    }

    StringBuilder originalOriginalTextMe = new StringBuilder();
    StringBuilder originalOriginalTextSp = new StringBuilder();
    private void recordContent() {
        final StringBuilder originalOriginalTextMe = new StringBuilder();
        final StringBuilder originalOriginalTextSp = new StringBuilder();
        if(subsectionList.size() > 1){
            for (int i=0;i<subsectionList.size()-1;i++){
                Subsection subsection = subsectionList.get(i);
                originalOriginalTextSp.append(subsection.originalContent);
                originalOriginalTextSp.append("\n\n");

                originalOriginalTextMe.append(subsection.originalContent);
                originalOriginalTextMe.append("\n");
                originalOriginalTextMe.append(subsection.translateContent);
                originalOriginalTextMe.append("\n\n");
            }
        }
        this.originalOriginalTextMe = originalOriginalTextMe;
        this.originalOriginalTextSp = originalOriginalTextSp;
    }

    public void changeHintText(){
        int tag = (int) btnTransform.getTag();
        if(!switchView.isChecked() && tag == 2){
            mHandler.post(()->{
                //刷新显示内容
                String originalHint;
                if(switchView.isChecked()){
                    originalHint = "此处说："+ mDataModel.getLanguageFrom().getValue().getName();
                }else {
                    originalHint = "此处说："+ mDataModel.getLanguageFrom().getValue().getName()
                            + "\n"
                            + "双语对照显示："+ mDataModel.getLanguageFrom().getValue().getName()
                            +"&"+ mDataModel.getLanguageTo().getValue().getName() ;
                }
                translationText.setHint(originalHint);
                originalText.setHint("译文显示："+ mDataModel.getLanguageTo().getValue().getName());
            });
        }else {
            mHandler.post(()->{
                //刷新显示内容
                String originalHint;
                if(switchView.isChecked()){
                    originalHint = "此处说："+ mDataModel.getLanguageFrom().getValue().getName();
                }else {
                    originalHint = "此处说："+ mDataModel.getLanguageFrom().getValue().getName()
                            + "\n"
                            + "双语对照显示："+ mDataModel.getLanguageFrom().getValue().getName()
                            +"&"+ mDataModel.getLanguageTo().getValue().getName() ;
                }
                originalText.setHint(originalHint);
                translationText.setHint("译文显示："+ mDataModel.getLanguageTo().getValue().getName());
            });
        }
    }

    private void changeOriginalText(String msg) {
        String result = getString(msg);
        if(TextUtils.isEmpty(result.trim()))return;
        int tag = (int) btnTransform.getTag();
        if(!switchView.isChecked() && tag == 2){
            translationText.setText(result);
            //滑到底
            ViewParent parent = translationText.getParent();
            if (parent instanceof NestedScrollView) {
                NestedScrollView scrollView = (NestedScrollView) parent;
                mHandler.postDelayed(()->scrollView.fullScroll(View.FOCUS_DOWN), 10);
            }
        }else {
            originalText.setText(result);
            //滑到底
            ViewParent parent = originalText.getParent();
            if (parent instanceof NestedScrollView) {
                NestedScrollView scrollView = (NestedScrollView) parent;
                mHandler.postDelayed(()->scrollView.fullScroll(View.FOCUS_DOWN), 10);
            }
        }
    }

    private @NonNull String getString(String msg) {
        StringBuilder originalTextBuilder = new StringBuilder();
        Subsection subsection = subsectionList.get(subsectionList.size()-1);
        if(switchView.isChecked()){
            originalTextBuilder.append(originalOriginalTextSp);
            originalTextBuilder.append(subsection.originalContent);
            originalTextBuilder.append(msg);
        }else {
            originalTextBuilder.append(originalOriginalTextMe);
            originalTextBuilder.append(subsection.originalContent);
            originalTextBuilder.append(msg);
            originalTextBuilder.append("\n");
            originalTextBuilder.append(subsection.translateContent);
        }
        //originalTextBuilder.append("\n\n");
        String result = originalTextBuilder.toString();
        return result;
    }

    private void changeTranslationText() {
        StringBuilder translationTextBuilder = new StringBuilder();
        for(int i=0;i<subsectionList.size();i++){
            Subsection subsection = subsectionList.get(i);
            translationTextBuilder.append(subsection.translateContent);
            if(i < subsectionList.size()-1){
                translationTextBuilder.append("\n\n");
            }
        }

        String result = translationTextBuilder.toString();
        if(TextUtils.isEmpty(result.trim()))return;
        if(switchView.isChecked()){
            translationText.setText(result);
            //滑到底
            ViewParent parent = translationText.getParent();
            if (parent instanceof NestedScrollView) {
                NestedScrollView scrollView = (NestedScrollView) parent;
                mHandler.postDelayed(()->scrollView.fullScroll(View.FOCUS_DOWN), 150);
            }
        }
    }


    private boolean isRotate;

    @Override
    public void onClick(View v) {
        if(XClickUtil.isFastDoubleClick(v,XClickUtil.INTERVAL_MILLIS)){
            return;
        }
        hideTips2();//有其它操作，隐藏提示
        int id = v.getId();
        if (id == R.id.ic_rotate) {
            if (mActivity.isLimitUsed("同声传译_屏幕旋转")) {
                if (!isRotate) {
                    rotateLayout.setRotation(180);
                    rotate.setRotation(180);
                } else {
                    rotateLayout.setRotation(0);
                    rotate.setRotation(0);
                }
                isRotate = !isRotate;
                toTalkingTips(isStarting);
            }
        } else if (id == R.id.copy_original) {
            if (mActivity.isLimitUsed("同声传译_原文复制")) {
                if (!TextUtils.isEmpty(originalText.getText())) {
                    //埋点
                    TranslationInterior.getTrackerListener().click(
                            TrackerForTrans.TSCY,
                            switchView.isChecked()?TrackerForTrans.COPY_ORIGINAL_CONTENT:TrackerForTrans.COPY_MERGE_CONTENT
                    );
                    ClipData mClipData = ClipData.newPlainText("Label", originalText.getText());
                    clipMgr.setPrimaryClip(mClipData);
                    Toast.makeText(mActivity, "文字已复制", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (id == R.id.copy_translated) {
            if (mActivity.isLimitUsed("同声传译_译文复制")) {
                if (!TextUtils.isEmpty(translationText.getText())) {
                    //埋点
                    TranslationInterior.getTrackerListener().click(
                            TrackerForTrans.TSCY,
                            TrackerForTrans.COPY_TRANS_CONTENT
                    );
                    ClipData mClipData = ClipData.newPlainText("Label", translationText.getText());
                    clipMgr.setPrimaryClip(mClipData);
                    Toast.makeText(mActivity, "文字已复制", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (id == R.id.iv_start_and_stop) {
            //埋点
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    isStarting?TrackerForTrans.RECORD_STOP:TrackerForTrans.RECORD_START,
                    TrackerForTrans.RECORD
            );

            if (!mActivity.isLimitUsed(EventCode.SIMUL_TRANSLATE)) {
                return;
            }

            Drawable drawable = ivStartAndStop.getDrawable();
            if(isStarting){//暂停
                showTips2();
                isStarting = false;
                toTalkingTips(false);
                drawable.setLevel(2);

                stopRecord();

                timeChronometer.stop();
                animationDrawable.stop();
                waveLine.setBackgroundResource(R.drawable.ic_line);
                mHandler.post(hideToastRunnable);
                rlLang.setVisibility(View.VISIBLE);

                showLottieAnimation1(false);
                showLottieAnimation2(false);
                radioButton.setAlpha(1.0f);
            }else {//恢复播放
                if (mActivity.isLimitUsed(EventCode.SIMUL_TRANSLATE)) {
                    isStarting = true;
                    toTalkingTips(true);
                    drawable.setLevel(1);

                    executeRecognize(false);
                    waveLine.setBackground(animationDrawable);
                    animationDrawable.start();
                    rlLang.setVisibility(View.GONE);

                    showLottieAnimation1(switchView.isChecked());
                    showLottieAnimation2(!switchView.isChecked());
                    radioButton.setAlpha(0.5f);
                }
            }
            mHandler.removeCallbacks(showTipsRunnable);
            mHandler.post(showTipsRunnable);
            ivStartAndStop.setImageDrawable(drawable);
        }else if (id == R.id.left_bt) {
            mActivity.showLanguageDialog(true);
        } else if (id == R.id.right_bt) {
            mActivity.showLanguageDialog(false);
        } else if (id == R.id.icon_exchange) {
            showTranslateAnimation();
        } else if (id == R.id.radio_button) {
            if(radioButton.getAlpha() == 1f){
                if(mActivity.isLimitUsed("同声传译_录音")){
                    isAllowSaveRecording = !isAllowSaveRecording;
                    radioButton.setSelected(isAllowSaveRecording);
                    updateButton(2);
                }
            }else {
                ToastUtils.showNormal("录音中无法修改设置");
            }
        } else if (id == R.id.masked_view || id == R.id.masked_view2){
            mActivity.isLimitUsed("同声传译_查看结果");
        } else if (id == R.id.btn_transform){
            //埋点
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    TrackerForTrans.TRANSFORM
            );
            int tag = (int) btnTransform.getTag();
            if(tag == 1){
                tag = 2;
            }else {
                tag = 1;
            }
            btnTransform.setTag(tag);
            btnTransform.setImageLevel(tag);
            transform();
        }
    }

    public void stopRecording(){
        if(isStarting){
            ivStartAndStop.performClick();
        }
    }

    private void showTips2() {
        if(!isAllowSaveRecording && !showItFirstTime){
            showItFirstTime = true;
            tvTips2.setVisibility(View.VISIBLE);
        }
    }
    private void hideTips2() {
        tvTips2.setVisibility(View.GONE);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void updateButton(int level){
        if(isAllowSaveRecording){
            ivStartAndStop.setImageResource(R.drawable.ic_stop_and_start_red);
        }else {
            ivStartAndStop.setImageResource(R.drawable.ic_stop_and_start);
        }
        Drawable drawable = ivStartAndStop.getDrawable();
        drawable.setLevel(level);
        ivStartAndStop.setImageDrawable(drawable);
    }

    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, fromBt.getWidth() + exchange.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        fromBt.startAnimation(ta1);
        fromBt.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -toBt.getWidth()-exchange.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        toBt.startAnimation(ta2);
        toBt.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                animation.cancel();

                changeHintText();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    //设置颜色
    private void setThemeColor() {
        parentLayout.setBackgroundColor(TranslationInterior.getThemeColor());
        copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
        copyTranslated.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
        translationText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    copyTranslated.setEnabled(false);
                    parsingLayout.setVisibility(View.VISIBLE);
                    copyTranslated.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
                } else {
                    parsingLayout.setVisibility(View.GONE);
                    copyTranslated.setEnabled(true);
                    copyTranslated.setImageTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        originalText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    parsingLayout2.setVisibility(View.VISIBLE);
                    copyOriginal.setEnabled(false);
                    copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
                } else {
                    parsingLayout2.setVisibility(View.GONE);
                    copyOriginal.setEnabled(true);
                    copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#ffffff")));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setShowLottieAnimation(boolean isChecked){

        //内容窗口动画
        if(isChecked){
            mHandler.removeCallbacks(hideBottomAnimation);
            mHandler.removeCallbacks(showBottomAnimation);
            mHandler.post(showBottomAnimation);
        }else {
            //埋点
            TranslationInterior.getTrackerListener().view(TrackerForTrans.VIEW_MERGE_SHOW);
            mHandler.removeCallbacks(hideBottomAnimation);
            mHandler.removeCallbacks(showBottomAnimation);
            mHandler.post(hideBottomAnimation);
        }

        transform();

        //Lottie动画
        showLottieAnimation1(isChecked);
        showLottieAnimation2(!isChecked);

        //文本框滑动到底部内容
        originalScroll.postDelayed(() -> originalScroll.fullScroll(View.FOCUS_DOWN), 1000);
        transScroll.postDelayed(() -> transScroll.fullScroll(View.FOCUS_DOWN), 1000);
    }

    private Runnable showBottomAnimation = new Runnable() {

        @Override
        public void run() {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
            if(params.weight<1){
                params.weight += 0.05f;
                bottomLayout.setLayoutParams(params);
                mHandler.postDelayed(this,5);
            }else {
                params.weight = 1.0f;
                bottomLayout.setLayoutParams(params);
            }
            bottomLayout.invalidate();
        }
    };
    private Runnable hideBottomAnimation = new Runnable() {

        @Override
        public void run() {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
            if(params.weight<=1 && params.weight> 0){
                params.weight -= 0.05f;
                bottomLayout.setLayoutParams(params);
                mHandler.postDelayed(this,5);
            }else {
                params.weight = 0f;
                bottomLayout.setLayoutParams(params);
            }
            bottomLayout.invalidate();
        }
    };

    private void showLottieAnimation1(boolean allowShow) {
        if(allowShow && isStarting && TextUtils.isEmpty(translationText.getText().toString().trim())){
            parsingLayout.setVisibility(View.VISIBLE);
            lottie1.playAnimation();
        }else {
            parsingLayout.setVisibility(View.GONE);
            lottie1.pauseAnimation();
        }

    }

    private void showLottieAnimation2(boolean allowShow) {
        if(allowShow && isStarting && TextUtils.isEmpty(originalText.getText().toString().trim())){
            parsingLayout2.setVisibility(View.VISIBLE);
            lottie2.playAnimation();
        }else {
            parsingLayout2.setVisibility(View.GONE);
            lottie2.pauseAnimation();
        }
    }

    private class Subsection implements Cloneable {
        private String originalContent = "";
        private String translateContent = "";

        public Subsection() {
        }

        public Subsection(String originalContent, String translateContent) {
            this.originalContent = originalContent;
            this.translateContent = translateContent;
        }

        public String getOriginalContent() {
            return originalContent;
        }

        public void setOriginalContent(String originalContent) {
            this.originalContent = originalContent;
        }

        public String getTranslateContent() {
            return translateContent;
        }

        public void setTranslateContent(String translateContent) {
            this.translateContent = translateContent;
        }

        @NonNull
        @NotNull
        @Override
        protected Subsection clone() throws CloneNotSupportedException {
            return (Subsection) super.clone();
        }
    }
}
